package edu.ucla.cs.typecast.util.slf;

import java.io.*;
import java.util.*;

import junit.framework.TestCase;

public class ScriptLogTestCase extends TestCase {
	protected String getSimpleScript() {
		return "name = x31" + "\n" + "cpu = pentium m" + "\n" + "ram = ddr"
				+ "\n" + "hdd = small" + "\n" + "%" + "\n" + "name = x61"
				+ "\n" + "cpu = core 2 duo" + "\n" + "ram = ddr2" + "\n"
				+ "hdd = large" + "\n";
	}
	
	protected String getGarbageScript() {
		return getSimpleScript() + "equal_sign_missing" + "\n";
	}

	protected Map<String, String> getSimpleScriptExpectedEntry1() {
		Map<String, String> entry = new HashMap<String, String>();
		entry.put("name", "x31");
		entry.put("cpu", "pentium m");
		entry.put("ram", "ddr");
		entry.put("hdd", "small");
		return entry;
	}

	protected Map<String, String> getSimpleScriptExpectedEntry2() {
		Map<String, String> entry = new HashMap<String, String>();
		entry.put("name", "x61");
		entry.put("cpu", "core 2 duo");
		entry.put("ram", "ddr2");
		entry.put("hdd", "large");
		return entry;
	}

	public void testReadSimpleScript() throws IOException {
		ScriptLogReader slfr = new ScriptLogReader(getSimpleScript(), true);

		assertEquals(getSimpleScriptExpectedEntry1(), slfr.readEntry());
		assertEquals(getSimpleScriptExpectedEntry2(), slfr.readEntry());

		assertEquals(null, slfr.readEntry());
		assertEquals(null, slfr.readEntry());
		assertEquals(null, slfr.readEntry());
	}
	
	public void testReadGarbageScriptWithStrict() throws IOException {
		try {
			ScriptLogReader slfr = new ScriptLogReader(getGarbageScript(), true);
			
			assertEquals(getSimpleScriptExpectedEntry1(), slfr.readEntry());
			slfr.readEntry();
			fail("Strict mode did not catch the garbage entry");
		}
		catch (ScriptLogParseException e) {
			// Works as expected
		}
	}
	
	public void testReadGarbageScriptNoStrict() throws IOException {
		ScriptLogReader slfr = new ScriptLogReader(getGarbageScript(), false);
		
		assertEquals(getSimpleScriptExpectedEntry1(), slfr.readEntry());
		assertEquals(getSimpleScriptExpectedEntry2(), slfr.readEntry());
	}

	public void testWriteSimpleScript() throws IOException {
		StringWriter sw = new StringWriter();

		ScriptLogWriter slw = new ScriptLogWriter(sw);
		slw.writeEntry(getSimpleScriptExpectedEntry1());
		slw.writeEntry(getSimpleScriptExpectedEntry2());
		slw.close();

		assertEquals(getSimpleScript().length(), sw.toString().length());

		ScriptLogReader slfr = new ScriptLogReader(sw.toString(), true);

		assertEquals(getSimpleScriptExpectedEntry1(), slfr.readEntry());
		assertEquals(getSimpleScriptExpectedEntry2(), slfr.readEntry());
	}
}
